package com.example.demo.thread.ch4.case02;

import java.io.InputStream;

/**
 * 基于任务分割实现的统计
 *
 * @author: htc
 * @date: Created in 16:39 2019/1/9.
 */
public class MultiThreadedStatTask extends AbstractStatTask {
    /**
     * 日志文件输入缓冲大小
     */
    protected final int inputBufferSize;
    /**
     * 日志记录集大小
     */
    protected final int batchSize;
    /**
     * 日志文件输入流
     */
    protected final InputStream in;

    /**
     * 实例初始化块
     */ {
//        String strBufferSize = System.getProperty("x.input.buffer");
        String strBufferSize = "8192";
        inputBufferSize = null != strBufferSize ? Integer.valueOf(strBufferSize) : 8192;
//        String strBatchSize = System.getProperty("x.batch.buffer");
        String strBatchSize = "2000";
        batchSize = null != strBatchSize ? Integer.valueOf(strBatchSize) : 2000;
    }

    public MultiThreadedStatTask(int sampleInterval, StatProcessor recordProcessor) {
        super(sampleInterval, recordProcessor);
        this.in = null;
    }

    public MultiThreadedStatTask(InputStream in, int sampleInterval, int traceIdDiff, String expectedOperationName, String expectedExternalDeviceList) {
        super(sampleInterval, traceIdDiff, expectedOperationName, expectedExternalDeviceList);
        this.in = in;
    }

    @Override
    protected void doCalculate() throws InterruptedException {
        final AbstractLogReader logReaderThread = createLogReader();
        //启动工作者线程
        logReaderThread.start();
        RecordSet recordSet;
        String record;
        for (; ; ) {
            recordSet = logReaderThread.nextBatch();
            if (null == recordSet) {
                break;
            }
            while (null != (record = recordSet.nextRecord())) {
                //实例变量recordProcessor是在AbstractStatTask中定义的
                recordProcessor.process(record);
            }
        }
    }

    protected AbstractLogReader createLogReader() {
         AbstractLogReader logReader = new LogReaderThread(in, inputBufferSize, batchSize);
         return logReader;
    }
}
